package com.le.tester.utils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Hashtable;
import java.util.Objects;
import java.util.UUID;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.QRCode;
import groovyjarjarantlr.InputBuffer;
import io.netty.util.internal.ThreadLocalRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;

/**
 * createTime：2022/9/9 14:13
 * description：生成二维码，返回InputStream,直接上传至oss,不存储在本地
 */
public class QRCodeUtil {

    private static final Logger LOG = LoggerFactory.getLogger(QRCodeUtil.class);

    //文字生成二维码
    private static BufferedImage createImage(String content, int widthParam, int heightParam) {
        try {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8);
            hints.put(EncodeHintType.MARGIN, 1);
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, widthParam, heightParam, hints);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
                            : 0xFFFFFFFF);
                }
            }
            return image;
        } catch (Exception e) {
            LOG.info("生成二维码异常：{}", e.getMessage());
            return null;
        }
    }

    //将生成得BufferedImage转成InputStream，用来上传oss
    public static InputStream changeBufferedImage(String content, int width, int height, String imageSuffix) {
        //InputStream byteIS = null;
        try (ByteArrayOutputStream byteOS = new ByteArrayOutputStream()) {
//            ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
            ImageIO.write(Objects.requireNonNull(createImage(content, width, height)), imageSuffix, byteOS);
            try (InputStream byteIS = new ByteArrayInputStream(byteOS.toByteArray())) {
                //byteOS.toString(String.valueOf(StandardCharsets.UTF_8));
                //not support throw exception
                //byteIS.reset();
                return byteIS;
            } finally {
                //设置count==0,清空占用的缓存
                byteOS.reset();
            }
            //byteIS = new ByteArrayInputStream(byteOS.toByteArray());
            //return byteIS;
        } catch (Exception e) {
            LOG.info("BufferedImage转换成InputStream异常：{}", e.getMessage());
            return null;
        }
//        } finally {
//            if (Objects.nonNull(byteIS)) {
//                byteIS.close();
//            }
//        }

    }

//    public static void main(String[] args) throws Exception {
//        String content = UUID.randomUUID().toString().substring(16);
//        System.out.println(QRCodeUtil.changeBufferedImage(content, 300, 300, "JPG"));
//    }

}
